﻿using Microsoft.AspNetCore.Mvc;
using AdminWeb.Models;
using Microsoft.AspNetCore.Authorization; 
using System.Diagnostics;
using XW.Web.Framework;
using XW.Web.Framework.Jwt;
using Microsoft.Extensions.Options;
using XW.Core;
using XW.Data;
using Microsoft.IdentityModel.Tokens;
using XW.Utils;
using System.Threading.Tasks;

namespace AdminWeb.Controllers
{
	/// <summary>
	/// 当前用户控制器
	/// </summary>
	/// <seealso cref="XW.Web.Framework.BaseController" />
	[Authorize]
	public class UserController :  BaseController
	{
		private readonly IOptions<JwtSecurityTokenOptions> _jwtOptions;
		private readonly ILogger<UserController> _logger;
		private readonly SqlSugarRepository<SysUser> _userRep;
        private readonly SqlSugarRepository<SysMenu> _menuRep;
        private readonly SqlSugarRepository<SysUserRole> _userRoleRep;
        private readonly SqlSugarRepository<SysRoleMenu> _roleMenuRep;
        public UserController(ILogger<UserController> logger, 
            IOptions<JwtSecurityTokenOptions> jwtOptions,
            SqlSugarRepository<SysUser> userRep,
            SqlSugarRepository<SysMenu> menuRep,
            SqlSugarRepository<SysUserRole> userRoleRep,
            SqlSugarRepository<SysRoleMenu> roleMenuRep)
		{
			_logger = logger;
			_jwtOptions = jwtOptions;
			_userRep = userRep;
            _menuRep = menuRep;
            _userRoleRep = userRoleRep;
            _roleMenuRep = roleMenuRep;
        }
		/// <summary>
		/// 基本资料
		/// </summary>
		/// <returns></returns>
		[Authorize]
		public IActionResult Setting()
		{
			var user = _userRep.GetById(this.UserId);
			//ViewData["CurrentUser"] = user;
			return View(user);
		}
        private List<object> GetChilds(long pid, List<SysMenu> ds)
        {
            List<object> result = new List<object>();
            var menus = ds.Where(d => d.ParentId == pid).OrderBy(d => d.Sort).ToList();
            foreach (var menu in menus)
            {
                var children = GetChilds(CommonHelper.ToInt64(menu.Id), ds);
                if (children.Count > 0)
                {
                    result.Add(new { id = menu.Id, icon = menu.Icon, title = menu.Name, href = menu.Url, target = "_self", permission = menu.permission, child = children });
                }
                else
                {
                    result.Add(new { id = menu.Id, icon = menu.Icon, title = menu.Name, href = menu.Url, target = "_self", permission = menu.permission});
                }
            }
            return result;
        }

        /// <summary>
        /// 网站初始化
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<IActionResult> SiteInit() {
            #region 菜单列表

            // var user = _userRep.GetById(this.UserId);
            // 获取用户角色
            var roles = await _userRoleRep.AsQueryable().Where(d => d.UserId == this.UserId).Select(d => d.RoleId).ToListAsync();
            // 获取用户菜单
            var menusIds = await _roleMenuRep.AsQueryable().Where(d => roles.Contains(d.RoleId)).Select(d => d.MenuId).ToListAsync();
            var menus =  _menuRep.AsQueryable().Where(d => d.IsDelete == false && d.IsShow == 1 && menusIds.Contains( d.Id)).ToList();
            var menuInfo = new List<object>();
            var childs = GetChilds(0, menus);
            foreach (var menu in childs)
            {
                menuInfo.Add(menu);
            }
            //menuInfo.Add(new
            //{
            //    title = "系统管理",
            //    icon = "fa fa-address-book",
            //    href = "",
            //    target = "_self",
            //    child = new List<Object>{
            //       new {
            //         title = "用户管理",
            //         href = "Sys/User/List",
            //         icon = "fa fa-window-maximize",
            //         target = "_self"
            //       },
            //       new {
            //         title = "菜单管理",
            //         href = "Sys/Menu/List",
            //         icon = "fa fa-window-maximize",
            //         target = "_self"
            //       },
            //       new {
            //         title = "角色管理",
            //         href = "Sys/Role/List",
            //         icon = "fa fa-window-maximize",
            //         target = "_self"
            //       }
            //     }
            //});
            //menuInfo.Add(new
            //{
            //    title = "用户管理",
            //    icon = "fa fa-window-maximize",
            //    href = "Sys/User/List",
            //    target = "_self"
            //});

            #region 例子菜单
            menuInfo.Add(
                  new
                  {
                      title = "常规管理",
                      icon = "fa fa-address-book",
                      href = "",
                      target = "_self",
                      child = new List<Object>{
                       new {
                         title = "主页模板",
                         href = "",
                         icon = "fa fa-home",
                         target = "_self",
                         child = new List<Object>{
                           new {
                             title = "主页一",
                             href = "layminiadmin/page/welcome-1.html",
                             icon = "fa fa-tachometer",
                             target = "_self"
                           },
                           new {
                             title = "主页二",
                             href = "layminiadmin/page/welcome-2.html",
                             icon = "fa fa-tachometer",
                             target = "_self"
                           },
                           new {
                             title = "主页三",
                             href = "layminiadmin/page/welcome-3.html",
                             icon = "fa fa-tachometer",
                             target = "_self"
                           }
                         }
                       },
                       new {
                         title = "菜单管理",
                         href = "layminiadmin/page/menu.html",
                         icon = "fa fa-window-maximize",
                         target = "_self"
                       },
                       new {
                         title = "系统设置",
                         href = "layminiadmin/page/setting.html",
                         icon = "fa fa-gears",
                         target = "_self"
                       },
                       new {
                         title = "表格示例",
                         href = "layminiadmin/page/table.html",
                         icon = "fa fa-file-text",
                         target = "_self"
                       },
                       new {
                         title = "表单示例",
                         href = "",
                         icon = "fa fa-calendar",
                         target = "_self",
                         child = new List<Object>{
                           new {
                             title = "普通表单",
                             href = "layminiadmin/page/form.html",
                             icon = "fa fa-list-alt",
                             target = "_self"
                           },
                           new {
                             title = "分步表单",
                             href = "layminiadmin/page/form-step.html",
                             icon = "fa fa-navicon",
                             target = "_self"
                           }
                         }
                       },
                       new {
                         title = "登录模板",
                         href = "",
                         icon = "fa fa-flag-o",
                         target = "_self",
                         child = new List<Object>{
                           new {
                             title = "登录-1",
                             href = "layminiadmin/page/login-1.html",
                             icon = "fa fa-stumbleupon-circle",
                             target = "_blank"
                           },
                           new {
                             title = "登录-2",
                             href = "layminiadmin/page/login-2.html",
                             icon = "fa fa-viacoin",
                             target = "_blank"
                           },
                           new {
                             title = "登录-3",
                             href = "layminiadmin/page/login-3.html",
                             icon = "fa fa-tags",
                             target = "_blank"
                           }
                         }
                       },
                       new {
                         title = "异常页面",
                         href = "",
                         icon = "fa fa-home",
                         target = "_self",
                         child = new List<Object>{
                           new {
                             title = "404页面",
                             href = "layminiadmin/page/404.html",
                             icon = "fa fa-hourglass-end",
                             target = "_self"
                           }
                         }
                       },
                       new {
                         title = "其它界面",
                         href = "",
                         icon = "fa fa-snowflake-o",
                         target = "",
                         child = new List<Object>{
                           new {
                             title = "按钮示例",
                             href = "layminiadmin/page/button.html",
                             icon = "fa fa-snowflake-o",
                             target = "_self"
                           },
                           new {
                             title = "弹出层",
                             href = "layminiadmin/page/layer.html",
                             icon = "fa fa-shield",
                             target = "_self"
                           }
                         }
                       }
                    }
                  });
            menuInfo.Add(new
            {
                title = "组件管理",
                icon = "fa fa-lemon-o",
                href = "",
                target = "_self",
                child = new List<Object>{
       new {
         title = "图标列表",
         href = "layminiadmin/page/icon.html",
         icon = "fa fa-dot-circle-o",
         target = "_self"
       },
       new {
         title = "图标选择",
         href = "layminiadmin/page/icon-picker.html",
         icon = "fa fa-adn",
         target = "_self"
       },
       new {
         title = "颜色选择",
         href = "layminiadmin/page/color-select.html",
         icon = "fa fa-dashboard",
         target = "_self"
       },
       new {
         title = "下拉选择",
         href = "layminiadmin/page/table-select.html",
         icon = "fa fa-angle-double-down",
         target = "_self"
       },
       new {
         title = "文件上传",
         href = "layminiadmin/page/upload.html",
         icon = "fa fa-arrow-up",
         target = "_self"
       },
       new {
         title = "富文本编辑器",
         href = "layminiadmin/page/editor.html",
         icon = "fa fa-edit",
         target = "_self"
       },
       new {
         title = "省市县区选择器",
         href = "layminiadmin/page/area.html",
         icon = "fa fa-rocket",
         target = "_self"
       }
     }
            });
            menuInfo.Add(new
            {
                title = "其它管理",
                icon = "fa fa-slideshare",
                href = "",
                target = "_self",
                child = new List<Object>{
       new {
         title = "多级菜单",
         href = "",
         icon = "fa fa-meetup",
         target = "",
         child = new List<Object>{
           new {
             title = "按钮1",
             href = "layminiadmin/page/button.html?v=1",
             icon = "fa fa-calendar",
             target = "_self",
             child = new List<Object>{
               new {
                 title = "按钮2",
                 href = "layminiadmin/page/button.html?v=2",
                 icon = "fa fa-snowflake-o",
                 target = "_self",
                 child = new List<Object>{
                   new {
                     title = "按钮3",
                     href = "layminiadmin/page/button.html?v=3",
                     icon = "fa fa-snowflake-o",
                     target = "_self"
                   },
                   new {
                     title = "表单4",
                     href = "layminiadmin/page/form.html?v=1",
                     icon = "fa fa-calendar",
                     target = "_self"
                   }
                 }
               }
             }
           }
         }
       },
       new {
         title = "失效菜单",
         href = "layminiadmin/page/error.html",
         icon = "fa fa-superpowers",
         target = "_self"
       },
       new {
         title = "聊天菜单",
         href = "layminiadmin/page/chat.html",
         icon = "fa fa-weixin",
         target = "_self"
       }
     }
            });
            #endregion

            #endregion

            var result = new
			{
                homeInfo = new {
                    title = "首页",
                    href = "layminiadmin/page/welcome-1.html?t=1"
                },

                logoInfo = new {
                    title = "后台管理系统",
                    image =  "logo.png",
                    href = "" 
                },
                menuInfo = menuInfo
            };
			return GetSuccessResult(result);
		}

        /// <summary>
        /// 菜单列表
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult VueMenuList() { 
        
            var data =    new List<object>();
            var menu1 = new
            {
                path = "/list",
                name = "list",
                component = "LAYOUT",
                redirect = "/list/base",
                meta = new
                {
                    title = new
                    {
                        zh_CN = "列表页",
                        en_US = "List",
                    },
                    icon = "view-list",
                },
                children = new List<object> {
               new {
                  path= "base",
                  name= "ListBase",
                  component= "/list/base/index",
                  meta= new {
                    title= new {
                      zh_CN= "基础列表页",
                      en_US= "Base List",
                    },
                  },
                },
                new {
                  path= "card",
                  name= "ListCard",
                  component= "/list/card/index",
                  meta= new {
                    title= new {
                      zh_CN= "卡片列表页",
                      en_US= "Card List",
                    },
                  },
                },
                new {
                  path= "filter",
                  name= "ListFilter",
                  component= "/list/filter/index",
                  meta= new {
                    title= new {
                      zh_CN= "筛选列表页",
                      en_US= "Filter List",
                    },
                  },
                },
                new {
                  path= "tree",
                  name= "ListTree",
                  component= "/list/tree/index",
                  meta= new {
                    title= new {
                      zh_CN= "树状筛选列表页",
                      en_US= "Tree List",
                    },
                  },
                },
              },
            };
            data.Add(menu1);
            return GetSuccessResult(data);
        }
    }
}
